var app = getApp(), fetchApi = require("../../../utils/httpPost.js"),
common_Js = require("../../../component/common.js");
const CryptoJS = require("../../../utils/aesUtil.js");
import Toast from '../../../component/vant/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgurl: app.getImgUrl(),
    current:0,
    state:0,
    pageSize:10,
    pageIndex:1,
    couponList:[],
    banners:[],
    tabIndex:0,
    hasData:false,
    netWork:true,
    isLoading:true,
    loading:false,
    couponNullText: ["您没有未使用蛋券", "您没有使用记录", "您没有过期蛋券", "暂无领蛋记录"],
    is_mer:0,
    
  },
  handleChange({ detail}) {
    var that = this
    that.data.state = detail.index
    var index = detail.index
    that.setData({
      current: detail.index,
      couponList:[],
      isLoading:true,
      hasData:false,
      pageIndex:1,
      tabIndex: index
    });
    if(index == 3){
      this.onHttpTicketRecord()
    }else{
      that.onHttpInit()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.onHttpInit()
  },
  reload:function(){
    this.onHttpInit()
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/eggTicket/list', {
      state: that.data.state,
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex
    }, function (res) {
      console.log("优惠券列表数据", res)
      if (res.data.code == 0) {
        if (res.data.totalcount > 0) {
          that.data.pageIndex += 1
          var coupons = res.data.data;
          if(coupons.length > 0){
            for (var index in coupons) {
              that.data.couponList.splice(that.data.couponList.length, 0, coupons[index]);
            }
            that.setData({ 
              hasData: true,
              couponList: that.data.couponList
            })
          }
        }
      }
      that.setData({ netWork: true, isLoading: false, loading: true})
    },function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, loading: false })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpTicketRecord: function () {
    var that = this
    fetchApi.httpPost('/eggTicket/exchange/record/list', {
      state: that.data.state,
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex,
      from_type:1//0 - 领券 1 - 用券（领蛋）
    }, function (res) {
      console.log("领券明细列表数据", res)
      if (res.data.code == 0) {
        if (res.data.totalcount > 0) {
          that.data.pageIndex += 1
          var coupons = res.data.data;
          if(coupons.length > 0){
            for (var index in coupons) {
              that.data.couponList.splice(that.data.couponList.length, 0, coupons[index]);
            }
            that.setData({ 
              hasData: true,
              couponList: that.data.couponList,
            })
          }
        }
      }
      that.setData({ netWork: true, isLoading: false, loading: true})
    },function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, loading: false })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  /**
   * 蛋票使用
   * @param {} res 
   */
  scanCodeDevice: function (res) {
    var ticketId = res.currentTarget.dataset.id;
    console.log('scanCode res',res)
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    that.data.from_page = 'scancode'
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }else {
      
      wx.scanCode({
        success: (res) => {
          console.log("扫码结果", res);
          var qrcontent = res.result;
          console.log('扫码结果',qrcontent)
          var q = "?" + qrcontent.split("?")[1];
          var json_param = common_Js.getQueryVariable(q);
          var linkParam = "qrtype=device&id=" + json_param.id;
          console.log('linkParam',linkParam)
          var device_id = json_param.id
          if(json_param.isEgg){
            linkParam += "&isEgg="+json_param.isEgg;
          }
          that.deviceOp(ticketId,device_id)
        },
        fail: (res) => { console.log(res); }
      })

    }
  },
  deviceOp:function(ticketId,device_id){
    fetchApi.httpPost('/device/detailById', {
      device_id: device_id,
    }, function (res) {
      console.log("设备信息", res)
      if (res.data.code == 0) {
        wx.navigateTo({ url: '/pagesDevice/pages/takeup/index?isEgg=1&id='+device_id+'&tid=' + ticketId })
        // if(eggCellCount > 0){
        //   wx.navigateTo({ url: '/pagesDevice/pages/device/takeup/index?isEgg=1&id=' + deviceId })
        // }else{
        //   Toast.fail("鸡蛋很抢手，已经被领完，等补给完再来哟~");
        // }
      } else {
        Toast.fail(res.data.msg);
      }
    }, function () { })
  },
  exchangeCoupon: function (e) {
    console.log('exchangeCoupon e', e)
    wx.navigateTo({
      url: '../exchangecoupon/index?coupon_id=' + e.currentTarget.dataset.couponid + '&user_coupon_id=' + e.currentTarget.dataset.id,
    })
  },
  presentCoupon: function (e) {
    console.log('presentCoupon e', e)
    wx.navigateTo({
      url: '/pages/present/index?coupon_id=' + e.currentTarget.dataset.couponid + '&user_coupon_id=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.pageIndex = 1
    this.setData({ couponList: []})
    if(this.data.state == 3){
      this.onHttpTicketRecord()
    }else{
      this.onHttpInit()
    }
  },
  /**
   * 页面上拉触底事件的处理函数    加载更多
   */
  onReachBottom: function () {
    if(this.data.state == 3){
      this.onHttpTicketRecord()
    }else{
      this.onHttpInit()
    }
  },
  onShow:function(){
    var that = this
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      this.setData({
        is_mer: app.getStorageSync("is_mer")
      })
      this.setData({
        current: 0,
        couponList: [],
        isLoading: true,
        hasData: false,
        pageIndex: 1,
        tabIndex: 0
      });
      if(this.data.state == 3){
        this.onHttpTicketRecord()
      }else{
        this.onHttpInit()
      }
    }
  }
})